package com.caiyi.financial.nirvana.sms.gateway.sgip.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class SGIPServerControlHandler extends ChannelDuplexHandler {
    private static final Logger logger = LoggerFactory.getLogger(SGIPServerControlHandler.class);

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise future) throws Exception {
        logger.info("正在连接");
        super.connect(ctx, remoteAddress, localAddress, future);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
        logger.info("正在关闭");
        super.close(ctx, future);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        super.write(ctx, msg, promise);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //IP查找对应网关设置成logout状态
        InetSocketAddress gateSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String gateAddr = gateSocket.getHostName();
        logger.info("服务器：" + gateAddr + " 连接断开【channelInactive】。channel:" + ctx.channel());
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error(cause.getMessage());
        cause.printStackTrace();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        InetSocketAddress gateSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String gateAddr = gateSocket.getHostName();
        logger.info("SGIP server to:" + gateAddr + " trig user event. now to close channle:" + ctx.channel());
        ctx.channel().close();
    }
}
